# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
from datetime import datetime,date
import time
#from odoo.addons.task_check_list.models.task_check_list import ProjectTask as CheckList

from odoo.exceptions import UserError


class ProjectBase(models.Model):
    _inherit = "project.project"

    def _compute_task_count(self):
        task_data = self.env['project.task'].read_group([('project_id', 'in', self.ids), '|', ('stage_id.fold', '=', False), ('stage_id', '=', False)], ['project_id'], ['project_id'])
        result = dict((data['project_id'][0], data['project_id_count']) for data in task_data)
        for project in self:
            project.task_count = result.get(project.id, 0)




class ProjectTask(models.Model):
    _inherit = 'project.task'

    @api.depends('task_checklist')
    def checklist_progress(self):
        """:return the value for the check list progress"""
        for rec in self:
            total_len = self.env['task.checklist'].search_count([])
            check_list_len = len(rec.task_checklist)
            if total_len != 0:
                rec.checklist_progress = (check_list_len * 100) / total_len
        if rec.checklist_progress == 100 and rec.project_id:
            fold_stages = rec.project_id.type_ids.filtered(lambda r: r.fold == True)
            if len(fold_stages)==0:
                raise UserError(_('Must have a complete stage be set fold'))
            rec.stage_id = fold_stages[0].id
            #rec.date_end = datetime.today()

    @api.depends('date_end')
    def get_points(self):
        for val in self:
            tmp = 0.0
            val.points = 0
            if  val.date_assign and  val.date_end and val.project_id:
                datetime_deadline = datetime.combine(val.date_deadline, datetime.max.time())
                duration_plan = val.project_id.resource_calendar_id.get_work_duration_data(val.date_assign,datetime_deadline)['days']
                duration_end = val.project_id.resource_calendar_id.get_work_duration_data(val.date_assign,val.date_end)['days']
                duration_plan = round(duration_plan *2)*0.5
                duration_end = round(duration_end *2)*0.5
                if duration_plan != 0:
                    val.points = 100 * duration_end / duration_plan
                    #val.points = (100.0*tmp) / duration



    checklist_progress = fields.Float(compute=checklist_progress, string='Check Progress', store=True, recompute=True, default=0.0)
    points = fields.Float(compute='get_points', digits=(3,2), string='deviation',store=True)
    task_level = fields.Float( default = '1.0',digits=(1,2), string='task important level')
    date_assign = fields.Datetime(string='Assigning Date', index=True, copy=False, readonly=True)


    @api.model
    def get_delay_days(self):
        for record in self:
                              
            delay_days = 0
            if record.date_end and record.date_deadline and record.project_id and (record.date_deadline < record.date_end.date() ):
                delay_days = record.project_id.resource_calendar_id.get_work_duration_data( datetime.combine(record.date_deadline, datetime.max.time()),record.date_end )['days']
                delay_days = round(delay_days *2)*0.5
            record.delay_days = abs(delay_days)


    @api.model
    def create(self, vals):
        if (not vals.get('date_assign')) and (vals.get('date_assign') is None):
            vals.update({'date_assign': datetime.today()})
        if (not vals.get('date_deadline')) and (vals.get('date_deadline')  is None ):
            vals.update({'date_deadline': datetime.now()})
        res = super(ProjectTask, self).create(vals)
        if (not vals.get('date_assign')) and (vals.get('date_assign') is not None):
            raise UserError(_("Kindly fill out the fields:date_assign."))
        if (not vals.get('date_deadline')) and (vals.get('date_deadline')  is not None ):
            raise UserError(_("kindly fill out the fields:date_deadline."))
        return res

    
    def write(self, vals):
        res = super(ProjectTask, self).write(vals)
        for dt in self:
            if (not dt.date_assign) and (dt.date_assign is not None):
                raise UserError(_("Kindly give the Assigning date for the task."))
            if (not dt.date_deadline) and (dt.date_deadline is not None):
                raise UserError(_("Kindly give the deadline for the task"))
            if dt.date_assign.date() > dt.date_deadline:
                raise UserError(_("Date Deadline should not be less than the Assigned Date."))
        return res

